﻿var gridRole, gridRight, toolbarOptions;
var selectedUserID, selectedRoleID;
var url = "RoleFunction.aspx?";
var userlistLoaded = false;
var permission = null;

$(document).ready(function () {
    permission = JSON.parse($("#hdPermission").val());
    permission.isSetupPermission = true;
    var layout = $("#layout").ligerLayout({
        //5分之3的高度
        bottomHeight: 3 * $(window).height() / 5,
        heightDiff: -6,
        allowBottomResize: false,
        allowCenterBottomResize: true,
        space: 5,
        onEndResize: updateGridHeight,
        onHeightChanged: updateGridHeight
    });
    var bottomHeader = $(".l-layout-bottom > .l-layout-header:first");
    var topHeader = $(".l-layout-center > .l-layout-header:first");
    bottomHeader.html('Permission Control');
    topHeader.html('Role');

    //Role 明细加载
    gridRole = $("#rolegrid").ligerGrid({
        columns: [
            { display: 'Role ID', name: 'RoleID', widht: 100, align: 'left' },
            { display: 'Role 描述', name: 'RoleDesc', width: 200, align: 'left' }
            ],
        toolbar: null,
        url: 'RoleFunction.aspx?Action=GetRolesList',
        width: '100%',
        height: 180,
        columnWidth: 100,
        showToggleColBtn: false,
        fixedCellHeight: true,
        frozen: false,
        usePager: false,
        checkbox: false,
        rownumbers: true
    });

    gridRole.bind('SelectRow', function (rowdata) {
        selectedUserID = null;
        selectedRoleID = rowdata.RoleID;
        gridRight.toggleCol('Forbid', false);

        bottomHeader.html("设置角色: 【" + rowdata.RoleDesc + "】权限");

        $.ligerDialog.waitting('Loading...');
        $.ajax({
            cache: false,
            async: true,
            url: url,
            data: { RoleID: selectedRoleID,
                Action: "GetRolePermission"
            },
            dataType: 'json',
            type: 'post',
            success: function (res) {
                var rows = gridRight.rows;
                var data = eval(res.Rows);
                //console.info(data);
                //处理data，合并相同ActID,Flag,FunID,RoleID


                for (var i = 0, l = rows.length; i < l; i++) {
                    rows[i].Permit = checkPermit(rows[i], data, i, false);
                }
                gridRight.reRender();
                for (var i = 0, l = rows.length; i < l; i++) {
                    checkPermit(rows[i], data, i, true);
                }
            },
            error: function (message) {

            },
            complete: function (XHR, TS) { $.ligerDialog.closeWaitting(); }
        });

    });




    //分配权限、禁止权限按钮的事件,注意jquery1.11已经去掉了live方法绑定事件，这里改为on
    //$("div.access-icon").on('click', function () {   
    //});

    $(document).on("click", "div.access-icon", function () {
        //alert('click');
        var selected = !$(this).hasClass("access-icon-selected");
        var ispermit = $(this).hasClass("access-permit");
        var rowid = $(this).attr("rowid");
        var rowdata = gridRight.records[rowid];
        if (ispermit) {
            f_Permit(rowdata, selected);
        }
        else {
            f_Forbid(rowdata, selected);
        }
    });

    loadToolbar();

    gridRightLoad(); //加载权限grid

    updateGridHeight();

});

//Setup Permission 按钮..需要保存权限
function loadToolbar() {
    if (permission.isEdit) {
        toolbarOptions = {
            items: [
            { text: '设置权限', click: f_save, img: "../Images/Save.ico" }
        ]
        };
    }
}


function gridRightLoad() {
    //console.info('load gridRight');
    //Function 明细加载
    gridRight = $("#rightgrid").ligerGrid({
        columns:
                [
                { display: 'Select', name: 'Permit', align: 'left', width: 60, minWidth: 60, isAllowHide: false, render: function (rowdata) {
                    var iconHtml = '<div class="access-icon access-permit';
                    if (rowdata.Permit)
                        iconHtml += " access-icon-selected";
                    iconHtml += '"';
                    iconHtml += ' rowid = "' + rowdata['__id'] + '"';
                    iconHtml += '></div>';
                    return iconHtml;
                }
                },
                { display: 'Function 描述', name: 'FunNm', align: 'left', width: 200, minWidth: 60 }
                ],
        showToggleColBtn: false, width: '99%', height: 200, rowHeight: 20, fixedCellHeight: true,
        columnWidth: 100, frozen: false, usePager: false, checkbox: false, rownumbers: true, toolbar: toolbarOptions,
        data: []
    });


    //加载 按钮数据
    $.ligerDialog.waitting('Loading...');
    $.ajax({
        cache: false,
        async: true,
        url: url,
        dataType: 'json',
        type: 'post',
        data: { Action: "LoadFun" },
        success: function (data) {
            gridRight.set('data', { Rows: eval(data.Rows) });

            //隐藏禁止权限列
            gridRight.toggleCol('Forbid', false);
        }
    });



    //加载列
    $.ajax({
        cache: false,
        async: true,
        url: url + "Action=LoadColumn",
        dataType: 'json',
        type: 'post',
        success: function (res) {
            //grid.loadData();
        },
        error: function (message) {
            var col = eval('(' + message.responseText + ')');

            gridRight.set('columns', col);
            gridRight.reRender();
        },
        complete: function (XHR, TS) { $.ligerDialog.closeWaitting(); }
    });

}



//判断是否有权限
function checkPermit(rowdata, data, rowID, flag) {
    if (!data || !data.length) return false;
    var isFunNm = rowdata.FunID != null && rowdata.FunID != '';
    for (var i = 0, l = data.length; i < l; i++) {
        if (isFunNm && data[i].FunID == rowdata.FunID) {
            if (flag) {
                var rID = '';
                if (rowID > 98)
                    rID = "r1" + (rowID + 1);
                else if (rowID > 8)
                    rID = "r10" + (rowID + 1);
                else
                    rID = "r100" + (rowID + 1);
                var Per = data[i].ActioinLst.split('/');

                for (var j = 0; j < Per.length; j++) {
                    $("table.l-grid-body-table tr[id='rightgrid|2|" + rID + "']  a").each(function () {
                        if (this.id == Per[j] && Per[j] != '') {
                            this.className = 'l-perm';
                        }
                    });
                }
            }
            return true;
        }
    }
    return false;
}




//保存
function f_save() {
    if (!selectedRoleID && !selectedUserID) return;
    var data = [];
    var strSel = '';
    var permissionlst = '';
    var actID = '';
    for (var i = 0, l = gridRight.rows.length; i < l; i++) {
        var o = $.extend({}, gridRight.rows[i]);
        o.Permit = o.Permit ? true : false;
        o.Forbid = o.Forbid ? true : false;
        o.FunID = o.FunID;
        o = gridRight.formatRecord(o, true);
        if (o.Permit) {
            var permissionlst = '';
            var actID = '';
            var rID = '';
            if (i > 98)
                rID = "r1" + (i + 1);
            else if (i > 8)
                rID = "r10" + (i + 1);
            else
                rID = "r100" + (i + 1);

            $("table.l-grid-body-table tr[id='rightgrid|2|" + rID + "']  a").each(function () {
                if (this.className == 'l-perm') {
                    permissionlst += this.innerText + '/';
                    actID += this.id + '/';

                }
            });
            if (permissionlst != '') {
                permissionlst = permissionlst.substr(0, permissionlst.length - 1);
                actID = actID.substr(0, actID.length - 1);
            }
            data.push({ RoleID: selectedRoleID, FunID: o.FunID, ActioinLst: actID });
        }
    }


    $.ajax({
        cache: false,
        async: true,
        url: url + 'Action=Save&roleid=' + selectedRoleID,
        data: {
            DataJSON: JSON.stringify(data)
        },
        dataType: 'text',
        type: 'post',
        success: function (res) {
            if (res == "") {
                toastrSuccess('Saved/保存成功!');
            }
            else {
                toastrError('Error! Not saved/保存失败!\n' + res);
                //LG.hideLoading();
            }
        },
        error: function (message) {
            if (message.responseText == "") {
                toastrSuccess('Saved/保存成功!');
                //LG.hideLoading();
            } else {
                toastrError('Error! Not saved/保存失败!');
                //LG.hideLoading();
            }
        }
    });
}






//为当前选择记录分配权限
//同时分配给下级记录
function f_Permit(rowdata, selected) {
    selected = selected ? true : false;
    rowdata.Permit = rowdata.Permit ? true : false;
    if (rowdata.Permit == selected) return;
    rowdata.Permit = selected;
    var children = gridRight.getChildren(rowdata);
    if (children) {
        for (var i = 0, l = children.length; i < l; i++) {
            f_Permit(children[i], selected);
        }
    }
    gridRight.reRender({ rowdata: rowdata });
}

//为当前选择记录禁止权限
//同时禁止下级记录权限
function f_Forbid(rowdata, selected) {
    selected = selected ? true : false;
    rowdata.Forbid = rowdata.Forbid ? true : false;
    if (rowdata.Forbid == selected) return;
    rowdata.Forbid = selected;
    if (selected) {
        var children = gridRight.getChildren(rowdata);
        if (children) {
            for (var i = 0, l = children.length; i < l; i++) {
                f_Forbid(children[i], selected);
            }
        }
    }
    gridRight.reRender({ rowdata: rowdata });
}




function PermClick(test) {
    if (test.document.activeElement.className == 'l-perm')
        test.document.activeElement.className = '';
    else
        test.document.activeElement.className = 'l-perm';
}



function updateGridHeight() {
    var topHeight = $("#layout > .l-layout-center").height();
    var bottomHeight = $("#layout > .l-layout-bottom").height();
    if (gridRole)
        gridRole.set('height', topHeight - 35);
    if (gridRight)
        gridRight.set('height', bottomHeight - 35);
}
